<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>截图案例</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        #body{
            width: 100%;
            background-image: url(./images/test.jpg);
            background-size: cover;
            min-height: 500px;
            background-position: center;
            background-repeat: no-repeat;
        }
        .btn{
            min-width: 120px;
            height: 45px;
            border-radius: 24.5px;
            background-color: blueviolet;
            font-size: 20px;
            color: #fff;
            margin:0 auto;
            text-align: center;
            line-height: 45px;
        }
        #body>p{
            display: block;
            height: 50px;
            min-width: 200px;
            color: #fff;
            font-size: 18px;
            margin:0 auto;
        } 
    </style>
</head>
<body>
    <div id="body">
        <p>hello this is htmlToCanvas</p>
    </div>
    <div class="btn">截图</div>
    <script src="./js/html2canvas.js"></script>
    <script>
        window.onload = function(){
            //截图配置
            function getImage() {
                html2canvas(document.getElementById('body')).then(
                    function(options){
                    setTimeout(function(){
                        downLoadImage(getCanvasToPng(options))
                    },1000)  
                }
                )
            }
            //监听事件
            let btn = document.querySelector('.btn')
            btn.addEventListener('click',getImage)
            //保存canvas为png
            function getCanvasToPng(canvas) {
                return canvas.toDataURL('image/png')
            }
            //保存canvas为jpg
            function getCanvasToJpg(canvas) {
               return canvas.toDataURL('image/jpg')
            }
            //下载图片
            function downLoadImage(url) {
                let oA = document.createElement('a');
                oA.download = '测试' // 设置下载的文件名，默认是'下载'
                oA.href = url
                document.body.appendChild(oA)
                oA.click();    //模拟a标签点击下载
                oA.remove();  //下载完成后从body移除
            }

        }
    </script>  
</body>
</html>